package util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;

public class MemcachedUtil {
	
	
	private static MemcachedClient mc;
	
	
	public static void initMemcached(String... servers) throws IOException{
		List<InetSocketAddress> address = new ArrayList<InetSocketAddress>();
		for(String server : servers){
			String[] add = server.split(":");
			if(add.length<2){
				break;
			}
			address.add(new InetSocketAddress(add[0], Integer.valueOf(add[1])));
		}
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(address);
		builder.setConnectionPoolSize(2);
		mc=builder.build();
		mc.setOpTimeout(3*60*1000);
	}
	
	public static boolean mc_replace(String key,int exp,Object val){
		if(mc==null)return false;
		try {
			return mc.replace(key, exp,val);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return false;
	}
	public static boolean mc_set(String key,int exp,Object val){
		if(mc==null)return false;
		try {
			return mc.set(key, exp,val);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public static <T> T  mc_get(String key){
		if(mc==null)return null;
		Object obj=null;
		try {
			obj = mc.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(obj==null)return null;
		return (T) obj;
	}
	public static boolean mc_delete(String key){
		if(mc==null)return false;
		try {
			return mc.delete(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
